/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.zt.dangyuan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import io.zt.dangyuan.customView.RefreshListView;
import io.zt.dangyuan.customView.SendEvent;
import io.zt.dangyuan.object.ContentListObject;
import io.zt.dangyuan.object.ContentListRequest;

/**
 * TODO
 */
public class BaseActivity extends AppCompatActivity {
    TextView abTitle;
    ImageView titleImg;
    Toolbar toolbar;
    RelativeLayout mContentFrgament;
    DrawerLayout mDrawerLayout;
    TextView noDataView;


    ContentListRequest contentListRequest;
    RefreshListView listView;
    BBSItemAdapter1 bbsMainAdapter2;
    List<ContentListObject.ListEntity> listObejects;

    String cid;
    int pageSize;


    Handler dataHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            Toast.makeText(BaseActivity.this, "已经没有更多数据了，亲", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        pageSize = 10;
//        contentListRequest.setTapType("1");
        initView();

        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_menu);
        // 初始化数据

        contentListRequest = new ContentListRequest();
        contentListRequest.setPageSize("10");
        contentListRequest.setTapType("1");
        listObejects = new ArrayList<ContentListObject.ListEntity>();

        if (abTitle != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }

    @Subscribe
    public void onEvent(SendEvent event) {
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void initView() {
        abTitle = (TextView) findViewById(R.id.toolbar_title);
        titleImg = (ImageView) findViewById(R.id.toolbar_title_img);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mContentFrgament = (RelativeLayout) findViewById(R.id.content_layout);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        noDataView = (TextView) findViewById(R.id.base_no_data_view);
    }

    public void OpenLeftMenu() {
        mDrawerLayout.openDrawer(Gravity.LEFT);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
                Gravity.LEFT);
    }

    public void addCenterView(int layout) {
        mContentFrgament.addView(getLayoutInflater().inflate(layout, null), RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

    }

    public void setTitleImg(int ResId) {
        titleImg.setVisibility(View.VISIBLE);
        abTitle.setVisibility(View.GONE);
        titleImg.setImageResource(ResId);
    }

    @Override
    public void setTitle(CharSequence title) {
        titleImg.setVisibility(View.GONE);
        abTitle.setVisibility(View.VISIBLE);
        abTitle.setText(title);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main_search, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                OpenLeftMenu();
                return true;
            case R.id.action_search:
                startActivity(new Intent(this, SearchActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void webRequst(boolean isshow) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("taptype", contentListRequest.getArcType());
        map.put("pagesize", "10");
        if (contentListRequest.getTapType().equals("1")) {
        } else {
            ContentListObject.ListEntity object = listObejects.get(listObejects.size() - 1);
            map.put("criticalid", String.valueOf(object.getArcId()));
            map.put("taptype", contentListRequest.getTapType());
        }
        if (contentListRequest.getSearchKey() != null) {
            String conmentStr = "";
            try {
                conmentStr = URLEncoder.encode(contentListRequest.getSearchKey(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            map.put("searchkey", conmentStr);
        }

        if (cid == null || cid.equals("")) {

        } else {
            map.put("cid", "djdt");
        }

        WebUtils.showProgress = isshow;
        WebUtils.sendPost(BaseActivity.this, "contentList", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {

                ContentListObject resultData = JSON.parseObject(data, ContentListObject.class);
                listObejects.addAll(resultData.getList());
                bbsMainAdapter2.notifyDataSetChanged();
                if (listObejects.size() == 0) {
                    noDataView.setVisibility(View.VISIBLE);
                } else {
                    noDataView.setVisibility(View.GONE);
                }

                //判断是否还有数据，如果没有就不再重复加载
                if (resultData.getList().size() < Constant.page) {
                    dataHandler.sendEmptyMessage(0);
                }
                listView.hideHeaderView();
                listView.hideFooterView();
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                System.out.print(error.getMessage().toString());
            }

        });


    }

//    public void doshare(String targetUrl, String imageUrl, String context, String title, UMShareListener umShareListener) {
//
//
//
//        final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
//                {
//                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
//                        SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
//                };
//        new ShareAction(this).setDisplayList(displaylist)
//                .withText(context)
//                .withTitle(title)
//                .withTargetUrl(targetUrl)
//                .withMedia(new UMImage(this, imageUrl))
//                /*.setListenerList(umShareListener)*/
//                .setCallback(umShareListener)
//                .open();
//    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}
